#coding:utf-8

"""
@author:自之梦 10061661
@time: 17/11/11 上午11:30
奇门接口测试demo
商家：ljj商家
"""
import random
import time
import requests
import uuid
import re
import threading
import json
from ContentDb import *
from xml_json import Xml2Json
from MyThread import MyThread
from log import *
from qm_auth import *
from TestData import *

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

result_order = []
base_url = " 127.0.0.1:7510"
time_str = time.strftime("%Y-%m-%d %H:%M:%S")
time_rod = str(uuid.uuid1())[10:25].replace("-","")
logger=logger("Main.qm_interface")


def build_uri(endpoint):
    return "/".join([base_url, endpoint])


def dataHeader(ordertype="deliveryorder.create", customerId="LJJ-T"):
    testdata = {"method":ordertype,
                "format":"xml",
                "app_key":"alogalog",
                "v":"2.4",
                "sign_method":"md5",
                "customerId":"{0}".format(customerId),
                "notifyId":str(time_rod),
                "timestamp":str(time_str)}
    return testdata


@logs(totaltime=True)
def qm_interface(method, orderType="", other_content="",itemCode="", warehouseCode="", ownerCode="", type="xml"):

    if other_content:
        content = other_content
        logger.info("Get ownerCode.")
        ownerCode = "".join(re.findall(r'<ownerCode>(.+?)</ownerCode>', content))#获取ownerCode
    else:
        logger.info("Connect mysql for get ownerCode.")
        content = sql_cont(method)
        itemCode = getSkus()
        # itemCode = ("SELECT * FROM goods WHERE id=5")[0][1]
        # itemCode="jittest_006"
        warehouseCode = getMerchant()[0]
        ownerCode = getMerchant()[1]
        if content is None:
            logger.error("Connect is none. Please check you input")
            result = "error: method={method}, orderType={orderType} has not found. Please check your input!".format(method=method, orderType=orderType)
            return result

    logger.info("config post headers.")
    testdata = dataHeader(method, customerId = ownerCode)
    
    #参数MD5加密
    try:
        logger.info("format content time_rod or time_str.")
        content=content.format(time_rod=time_rod, timestr=time_str, itemCode=itemCode, orderType=orderType, warehouseCode=warehouseCode, ownerCode=ownerCode)
    except Exception as e:
        logger.error("for conent failed %s "% e)
        pass

    logger.info("Get sign parms md5 value")
    testdata["sign"] = Ma5_Val(Data_Key_Sort(testdata) + content, "upper")
 
    logger.info("Assemble the complete URL")
    url = build_uri("qm-portal/rest.htm?{0}&outcode={1}").format(Key_Val_Sort(testdata), time_rod) 
    try : 
        logger.info("Send content for %s ." % url)
        r = requests.post(url, content)
    except Exception as e:
        logger.error("Send content failed %s ."% e)
        return e

    if type == "xml":
        print r.url
        data = r.text 
    elif type == "json":
        data = Xml2Json(r.text).result
        data['outcode'] = time_rod
        data = json.dumps(data, sort_keys=True, indent=4)
    logger.info("return data: %s" % data)
    return data


@logs(totaltime=True)
def qm_create_order():
    """
    奇门接口
    """
    time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    time_rod = str(uuid.uuid1())[10:25].replace("-","") + str(random.randint(10000, 90000))
    testdata = dataHeader("deliveryorder.create")
    content = '<?xml version="1.0" encoding="UTF-8"?><request><deliveryOrder><deliveryOrderCode>{time_rod}</deliveryOrderCode><orderType>JYCK</orderType>\
    <warehouseCode>LJJHN</warehouseCode>\
    <sourcePlatformCode>OTHER</sourcePlatformCode><createTime>{timestr}</createTime><placeOrderTime>{timestr}</placeOrderTime>\
    <operateTime>{timestr}</operateTime><shopNick>ll</shopNimck>\
    <totalAmount>6.65</totalAmount><itemAmount>6.64</itemAount><discountAmount>6.63</discountAmount><arAmount>6.62</arAmount><freight>6.61</freight>\
    <logisticsCode>YTO</logisticsCode><senderInfo><name>test</name>\
    <tel>02012345678</tel><mobile>13800138000</mobile><province>澳门</province><city>离岛</city><detailAddress>testdetailAddress</detailAddress></senderInfo><receiverInfo>\
    <name>我想说</name><tel>02012345678</tel><mobile>15001165221</mobile><province>澳门</province><city>离岛</city><detailAddress>办事处</detailAddress></receiverInfo></deliveryOrder>\
    <orderLines>\
    <orderLine><orderLineNo>{time_rod}1</orderLineNo><ownerCode>LJJ-T</ownerCode><itemCode>jittest_001</itemCode><inventoryType>ZP</inventoryType><planQty>3</planQty><actualPrice>3</actualPrice></orderLine>\
    </orderLines></request>'.format(time_rod=time_rod, timestr=time_str)
    testdata["sign"] = Ma5_Val(Data_Key_Sort(testdata) + content, "upper")
    url = build_uri("qm-portal/rest.htm?{0}").format(Key_Val_Sort(testdata))  

    r = requests.post(url, content)
    order_id = ''.join(re.findall(r'<deliveryOrderId>(.+?)</deliveryOrderId>', r.text.encode('utf-8')))
    if r.status_code and order_id:
        result_dit = {}
        result_dit["orderId"] = order_id
        result_order.append(result_dit)
        return sorted(result_order), len(result_order)
    else:
       return r.text,"deliveryOrderCode: {0}".format(time_rod)

@logs()
def common_get_req(url ,payload=""):
    if url:
        try:
            r = requests.get(url, params=payload )
            return r.content
        except Exception as e:
            return str(e)

@logs()
def com_post_req(url, payload):
    logger.info("   ")
    logger.info("start com_post_req func...")
    try:

        headers = {'content-type': 'application/json'}
        r = requests.post(url, data=json.dumps(payload), headers=headers)
        logger.info("com_post_req post header: %s ."% r.headers["content-type"])
        return r.content
    except Exception as e:
        return str(e)


def com_options_req(url):
    try:
        r = requests.options(url)
        return r.headers
    except Exception as e:
        return str(e)

if __name__ == "__main__":
    logger.info("Table created successfully")
    pass
    #商品同步接口 
    # qm_interface("singleitem.synchronize", orderType="add")

    #入库  
    # qm_interface("entryorder.create", orderType="CGRK")

    #出库  
    # qm_interface("stockout.create", orderType="B2BCK")

    #发货单创建 
    # qm_interface("deliveryorder.create", orderType="jyck")

    # data = {'key1': 'value1', 'key2': ['value2', 'value3']}
    # print common_get_req("1")
    # payload={'key1': 'value1', 'key2': 'value2'}
    # print com_post_req("http://httpbin.org/post", payload)
    # # print com_options_req("http://httpbin.org/get")

    # common_get_req("https://api.github.com/user")
#     other_content='<?xml version="1.0" encoding="UTF-8"?><request><deliveryOrder><deliveryOrderCode>{time_rod}</deliveryOrderCode><orderType>JYCK</orderType>\
# <warehouseCode>LJJHN</warehouseCode>\
# <sourcePlatformCode>OTHER</sourcePlatformCode><createTime>{timestr}</createTime><placeOrderTime>{timestr}</placeOrderTime>\
# <operateTime>{timestr}</operateTime><shopNick>ll</shopNick>\
# <totalAmount>6.65</totalAmount><itemAmount>6.64</itemAmount><discountAmount>6.63</discountAmount><arAmount>6.62</arAmount><freight>6.61</freight>\
# <logisticsCode>YTO</logisticsCode><senderInfo><name>test</name>\
# <tel>02012345678</tel><mobile>13800138000</mobile><province>澳门</province><city>离岛</city><detailAddress>testdetailAddress</detailAddress></senderInfo><receiverInfo>\
# <name>我想说</name><tel>02012345678</tel><mobile>15001165221</mobile><province>澳门</province><city>离岛</city><detailAddress>办事处</detailAddress></receiverInfo></deliveryOrder>\
# <orderLines>\
# <orderLine><orderLineNo>{time_rod}1</orderLineNo><ownerCode>LJJ-T</ownerCode><itemCode>jittest_001</itemCode><inventoryType>ZP</inventoryType><planQty>1</planQty><actualPrice>3</actualPrice></orderLine>\
# </orderLines></request>'
#     qm_interface("deliveryorder.create", other_content=other_content)
#     qm_interface("deliveryorder.create", orderType='jyck')

    # for _ in range(1):
    #     before_crea_order = get_sku_for_Db()
    #     threads = []
    #     NUM=3
    #     for i in range(NUM):
    #         t = MyThread(qm_create_order, name=qm_create_order.__name__)
    #         threads.append(t)
    #     for i in range(NUM):
    #         threads[i].start()
    #         # print threading.current_thread()
    #     for i in range(NUM):
    #         threads[i].join()

    #     print "before_crea_order: {0}".format(before_crea_order),"\n","after_crea_order: ",get_sku_for_Db()

    #取消订单 用other_content传参
#     other_content = '<?xml version="1.0" encoding="UTF-8"?><request>\
#   <warehouseCode>LJJHN</warehouseCode>\
#   <ownerCode>LJJ-T</ownerCode>\
#   <orderCode>WO20180118000002</orderCode>\
#   <orderId>WO20180118000002</orderId>\
#   <orderType>B2BCK</orderType>\
#   <cancelReason>test</cancelReason>\
# </request>'
  #qm_interface_sql("order.cancel", other_content=other_content) 

    #销退入库
    # content='<?xml version="1.0" encoding="UTF-8"?><request><returnOrder><returnOrderCode>OS20180118000013</returnOrderCode>\
    # <warehouseCode>LJJHN</warehouseCode><orderType>THRK</orderType><preDeliveryOrderCode>OS20180118000013</preDeliveryOrderCode>\
    # <preDeliveryOrderId>OS20180118000013</preDeliveryOrderId><logisticsCode>YTO</logisticsCode><senderInfo><name>test</name>\
    # <mobile>13800138000</mobile><province>广东</province><city>广州</city><detailAddress>detailAddress_test</detailAddress>\
    # </senderInfo></returnOrder><orderLines><orderLine><orderLineNo>1234</orderLineNo><ownerCode>LJJ-T</ownerCode>\
    # <itemCode>jittest_001</itemCode><inventoryType>ZP</inventoryType><planQty>3</planQty></orderLine></orderLines></request>'
    # qm_interface("returnorder.create", content)#
